import { Route, Switch, SwitchProps } from 'react-router-dom';
import type { RouteConfig } from './type';
/**
 *
 *
 * @param {*} props
 * @param {*} extraProps
 * @param {RouteConfig} route
 * @returns
 */
function RouteRenderComponent(route: RouteConfig, props: any, extraProps: any) {
  const { component: Component } = route;

  const newProps = { ...props, ...extraProps, route };
  if (Component) {
    // eslint-disable-next-line no-use-before-define
    const child = renderRoutes(route.routes ?? [], {}, { location: props.location });
    return <Component {...newProps}>{child}</Component>;
  }
  console.log(route);
  throw new Error('请输入路由的component');
}
/**
 * 渲染路由信息
 * @param {array} routes 需要渲染的路由配置
 * @param {object} extraProps 拖拽配置
 * @param {object} switchProps switch组件配置
 * @returns {any} 路由树
 */
function renderRoutes(routes: RouteConfig[], extraProps = {}, switchProps: SwitchProps = {}) {
  return routes ? (
    <Switch {...switchProps}>
      {routes.map((route, i) => (
        <Route
          key={route.key || i}
          path={route.path}
          exact={route.exact}
          strict={route.strict}
          render={(props) => {
            return RouteRenderComponent(route, props, extraProps);
          }}
        />
      ))}
    </Switch>
  ) : null;
}

export default renderRoutes;
